/*
 * @Author: taoyuqing
 * @Date: 2022-12-21 21:23:07
 * @Description: 首页
 */
import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:spree/pages/activity_page.dart';
import 'package:spree/pages/message_page.dart';
import 'package:spree/pages/profile_page.dart';
import 'package:spree/pages/vip_page.dart';
import '../provider/model/user_model.dart';
import '../utils/api.dart';
import 'home_page.dart';

class IndexPage extends StatefulWidget {
  IndexPage({Key? key}) : super(key: key);

  @override
  State<IndexPage> createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage>
    with AutomaticKeepAliveClientMixin {
  final List<Widget> pages = [
    HomePage(),
    ActivityPage(),
    VIPPage(),
    MessagePage(),
    ProfilePage()
  ];
  int _curIndex = 0;
  late PageController _controller;
  Map<String, dynamic> _deviceData = <String, dynamic>{};
  DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initPlatformState();
    _login(context);
    _controller = PageController(initialPage: _curIndex);
  }

  Future<void> initPlatformState() async {
    String deviceId = "";
    if (Platform.isIOS) {
      _deviceData = _readIosDeviceInfo(await deviceInfoPlugin.iosInfo);
      uploadIosDevice();
    } else if (Platform.isAndroid) {
      _deviceData = _readAndroidBuildData(await deviceInfoPlugin.androidInfo);
      uploadAndroidDevice();
    }
  }

  _login(BuildContext context) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      String? userName = prefs.getString('userName');
      String? passWord = prefs.getString('passWord');
      String? accessToken = prefs.getString("accessToken");
      dynamic user;
      if (accessToken == null || accessToken == '') {
        if (userName != "" && userName != null) {
          user = await Api.login({"userName": userName, "passWord": passWord});
          await prefs.setString('accessToken', user['data']['accessToken']);
        }
      } else {
        dynamic userInfoData = await Api.getInfo();
        dynamic userInfo = userInfoData['data'];
        dynamic userAccount = await Api.account();
        Provider.of<UserModel>(context, listen: false).setUserInfo(
            name: '${userInfo['nickname']}',
            id: '${userInfo['userId']}',
            mail: '${userInfo['email']}',
            imgUrl: '${userInfo['avatar']}',
            level: '${userInfo['vipLevel']}',
            token: accessToken,
            amount: '${userAccount['data']['accountAmount']}');
      }
    } catch (e) {
      print(e);
    }
  }

  uploadAndroidDevice() async {
    var deviceInfo = {
      "androidDTO": {
        "sdkInt": _deviceData['version.sdkInt'],
        "brand": _deviceData['brand'],
        "device": _deviceData['device'],
        "fingerprint": _deviceData['fingerprint'],
        "deviceId": _deviceData['id'],
        "manufacturer": _deviceData['manufacturer'],
        "model": _deviceData['model']
      }
    };
    final prefs = await SharedPreferences.getInstance();
    String? deviceId = prefs.getString("deviceId");
    if (deviceId == '' || deviceId == null) {
      Map result = await Api.uploadDeviceInfo(deviceInfo);
      String device_id = result['data'];
      prefs.setString("deviceId", device_id);
    }
  }

  uploadIosDevice() async {
    var deviceInfo = {
      "iosDTO": {
        "deviceName": _deviceData['name'],
        "systemName": _deviceData['systemName'],
        "systemVersion": _deviceData['systemVersion'],
        "model": _deviceData['model'],
        "identifierForVendor": _deviceData['identifierForVendor'],
        "releaseVersion": _deviceData['utsname.version']
      }
    };
    final prefs = await SharedPreferences.getInstance();
    String? deviceId = prefs.getString("deviceId");
    if (deviceId == '' || deviceId == null) {
      Map result = await Api.uploadDeviceInfo(deviceInfo);
      String device_id = result['data'];
      prefs.setString("deviceId", device_id);
    }
  }

  Map<String, dynamic> _readIosDeviceInfo(IosDeviceInfo data) {
    return <String, dynamic>{
      'name': data.name,
      'systemName': data.systemName,
      'systemVersion': data.systemVersion,
      'model': data.model,
      'localizedModel': data.localizedModel,
      'identifierForVendor': data.identifierForVendor,
      'isPhysicalDevice': data.isPhysicalDevice,
      'utsname.sysname': data.utsname.sysname,
      'utsname.nodename': data.utsname.nodename,
      'utsname.release': data.utsname.release,
      'utsname.version': data.utsname.version,
      'utsname.machine': data.utsname.machine,
    };
  }

  Map<String, dynamic> _readAndroidBuildData(AndroidDeviceInfo build) {
    return <String, dynamic>{
      'version.securityPatch': build.version.securityPatch,
      'version.sdkInt': build.version.sdkInt,
      'version.release': build.version.release,
      'version.previewSdkInt': build.version.previewSdkInt,
      'version.incremental': build.version.incremental,
      'version.codename': build.version.codename,
      'version.baseOS': build.version.baseOS,
      'board': build.board,
      'bootloader': build.bootloader,
      'brand': build.brand,
      'device': build.device,
      'display': build.display,
      'fingerprint': build.fingerprint,
      'hardware': build.hardware,
      'host': build.host,
      'id': build.id,
      'manufacturer': build.manufacturer,
      'model': build.model,
      'product': build.product,
      'supported32BitAbis': build.supported32BitAbis,
      'supported64BitAbis': build.supported64BitAbis,
      'supportedAbis': build.supportedAbis,
      'tags': build.tags,
      'type': build.type,
      'isPhysicalDevice': build.isPhysicalDevice,
      'systemFeatures': build.systemFeatures,
      'displaySizeInches':
          ((build.displayMetrics.sizeInches * 10).roundToDouble() / 10),
      'displayWidthPixels': build.displayMetrics.widthPx,
      'displayWidthInches': build.displayMetrics.widthInches,
      'displayHeightPixels': build.displayMetrics.heightPx,
      'displayHeightInches': build.displayMetrics.heightInches,
      'displayXDpi': build.displayMetrics.xDpi,
      'displayYDpi': build.displayMetrics.yDpi,
      'serialNumber': build.serialNumber,
    };
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        bottomNavigationBar: BottomNavigationBar(
          onTap: _onTap,
          type: BottomNavigationBarType.fixed,
          backgroundColor: Color(0xFF261E55),
          unselectedItemColor: Color(0xFFB0AFEC),
          selectedItemColor: Color(0xFFFFFFFF),
          items: [
            BottomNavigationBarItem(
                icon: _bottomNavigationBarItem(
                  imgPath: 'images/bottomNavi/Vector-unselect.png',
                ),
                activeIcon: _bottomNavigationBarItem(
                  imgPath: 'images/bottomNavi/Vector-select.png',
                ),
                label: 'Menu'),
            BottomNavigationBarItem(
                icon: _bottomNavigationBarItem(
                  imgPath: 'images/bottomNavi/Activity-unselect.png',
                ),
                activeIcon: _bottomNavigationBarItem(
                  imgPath: 'images/bottomNavi/Activity-select.png',
                ),
                label: "Activity"),
            BottomNavigationBarItem(
                icon: _bottomNavigationBarItem(
                  imgPath: 'images/bottomNavi/Vip-unselect.png',
                ),
                activeIcon: _bottomNavigationBarItem(
                  imgPath: 'images/bottomNavi/Vip-select.png',
                ),
                label: "VIP"),
            BottomNavigationBarItem(
                icon: Icon(Icons.message_rounded), label: "Message"),
            BottomNavigationBarItem(
                icon: _bottomNavigationBarItem(
                  imgPath: 'images/bottomNavi/Profile-unselect.png',
                ),
                activeIcon: _bottomNavigationBarItem(
                  imgPath: 'images/bottomNavi/Profile-select.png',
                ),
                label: "Profile"),
          ],
          currentIndex: _curIndex,
        ),
        body: PageView.builder(
          physics: NeverScrollableScrollPhysics(),
          controller: _controller,
          itemCount: pages.length,
          onPageChanged: _onPageChange,
          itemBuilder: (BuildContext context, int index) {
            return pages[index];
          },
        ));
  }

  void _onTap(int index) {
    _controller.jumpToPage(index);
  }

  void _onPageChange(int index) {
    if (index != _curIndex) {
      setState(() {
        _curIndex = index;
      });
    }
  }

  Widget _bottomNavigationBarItem({required String imgPath}) {
    return Image.asset(
      imgPath,
      width: 20,
      height: 20,
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
